package com.zam.web.sysController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zam.comment.Result;
import com.zam.mapper.MenuMapper;
import com.zam.mapper.SysRoleMenuMapper;
import com.zam.pojo.Menu;
import com.zam.pojo.SysRoleMenu;
import com.zam.service.ISysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/******************************
 controller层
 ******************************/
@RestController
@RequestMapping("/RMRelation")
public class SysRoleMenuController {
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    /*
    保存角色菜单关系
    */
    @PostMapping("/saveRelation/{roleID}")
    public Result saveRelation(@PathVariable Integer roleID, @RequestBody List<Integer> menuIDs) {
        sysRoleMenuService.removeByRoleId(roleID); //先删除原有数据（因为是双主键，不能使用mp中的方法）
        for (Integer menuID : menuIDs) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleID);
            sysRoleMenu.setMenuId(menuID);
            sysRoleMenuService.save(sysRoleMenu); //保存数据
        }
        return Result.success();
    }

    /*
        通过角色id查询角色菜单关系
    */
    @GetMapping("/findRelation/{roleID}")
    public Result findRelation(@PathVariable Integer roleID) {
        List<Integer> relationByRoleId = sysRoleMenuMapper.findRelationByRoleId(roleID);
        //获取到有二级菜单的一级菜单的id
        List<Integer> collect = menuMapper.selectList(
                new LambdaQueryWrapper<Menu>().eq(Menu::getPath, "")).stream()
                .map(Menu::getId).collect(Collectors.toList());
        //过滤掉一级菜单
        relationByRoleId= relationByRoleId.stream().filter(menuID -> !collect.contains(menuID)).collect(Collectors.toList());
        return Result.success(relationByRoleId);
    }

    /*
    添加数据
    */
    @PostMapping
    public boolean save(@RequestBody SysRoleMenu sysRoleMenu) {
        return sysRoleMenuService.saveOrUpdate(sysRoleMenu);
    }

    /*
    删除数据
    */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return sysRoleMenuService.removeById(id);
    }

    /*
    删除多个数据
    */
    @DeleteMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return sysRoleMenuService.removeByIds(ids);
    }

    /*
     查看全部
    */
    @GetMapping
    public List<SysRoleMenu> findAll() {
        return sysRoleMenuService.list();
    }

    /*
    根据id查看
    */
    @GetMapping("/{id}")
    public SysRoleMenu findOne(@PathVariable Integer id) {
        return sysRoleMenuService.getById(id);
    }

}

